package com.correo.socket.client;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.NoSuchAlgorithmException;

import com.correo.socket.client.beans.LoginBean;
import com.correo.socket.client.beans.ResponseLogin;
import com.correo.socket.client.beans.UsuarioValidado;
import com.correo.socket.ecriptar.ManagerMD5;

public class ClientSocketCorreo {

	private String 					ip;
	private int 					puerto;
	private ObjectInputStream 		ois;
	private ObjectOutputStream 		oos;
	private Socket 					socket;
	private String					usuario;
	private String 					pass;
	
	public ClientSocketCorreo(){
		
	}
	public ClientSocketCorreo(String ip,int puerto,String usuario, String pass){
		setIp(ip);
		setPuerto(puerto);
		setUsuario(usuario);
		setPass(pass);
	}
	
	public UsuarioValidado enviar(){
		LoginBean login = new LoginBean(usuario,pass);
		try 
		{
			socket = new Socket(ip,puerto);
			ois = new ObjectInputStream(socket.getInputStream());
			oos = new ObjectOutputStream(socket.getOutputStream());
			/*Leo*/
			//msg = (LoginBean)ois.readObject();
			//System.out.println(msg.getMensaje().toString());
			/*Grabo*/
			//msg.setTipoMensaje(1);
			//msg.setMensaje(socket.getInetAddress());
			oos.writeObject(login);
			/*Leo*/
			login = (LoginBean)ois.readObject();
			if(login.getMsgError()!=null){
				System.out.println(login.getMsgError());
			}else{
				System.out.println("login.getChallenge :"+login.getChallenge());
				oos.writeObject(new ResponseLogin(
								ManagerMD5.convertir(login.getChallenge()+
										login.getFechaActual()+
								login.getPassword())));
			}
			UsuarioValidado user = (UsuarioValidado)ois.readObject();
			
			ois.close();
			oos.close();
			socket.close();
			
			return user;
		} 
		catch (UnknownHostException e) 
		{	
			e.printStackTrace();
		} 
		catch (IOException e) 
		{	
			e.printStackTrace();
		} 
		catch (ClassNotFoundException e) 
		{
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}		
	
	
	
	
	public String getIp() {
		return ip;
	}
	public void setIp(String ip) {
		this.ip = ip;
	}
	public int getPuerto() {
		return puerto;
	}
	public void setPuerto(int puerto) {
		this.puerto = puerto;
	}
	public String getUsuario() {
		return usuario;
	}
	public void setUsuario(String usuario) {
		this.usuario = usuario;
	}
	public String getPass() {
		return pass;
	}
	public void setPass(String pass) {
		this.pass = pass;
	}
	
}
